<template>
  <el-dialog :model-value="dialogVisible" :title="dialogDatas.title" :destroy-on-close="true" @close="closeDialog">
    <div>
      <el-form style="height:300px;overflow: auto;" ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" :disabled="dialogDatas?.type == 'check'">
        <el-form-item label="设备ID" prop="deviceId">
          <el-input v-model="ruleForm.deviceId" placeholder="请输入设备ID"  clearable maxlength="10" />
        </el-form-item>
        <el-form-item label="归属组织机构" prop="orgId">
          <el-select v-model="ruleForm.orgId" class="w-full" placeholder="请选择归属组织机构" @change="changeOrgId" v-if="showOrg">
            <el-option v-for="(item) in orgIdDatas" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="归属检测点" prop="checkPointsId">
          <el-select v-model="ruleForm.checkPointsId" class="w-full" placeholder="请选择归属检测点" v-if="showOrgs">
            <el-option v-for="(item) in checkPointsOptionsDatas" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="ruleForm.deviceType" class="w-full" placeholder="请选择设备类型" v-if="showOrg">
            <el-option v-for="(item) in enumListTypeDatas" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="启用状态" prop="status">
          <el-select v-model="ruleForm.status" class="w-full" placeholder="请选择启用状态" v-if="showOrg">
            <el-option v-for="(item) in enumListDatas" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer v-if="!(dialogDatas?.type == 'check')">
      <span class="dialog-footer" style="display: block;text-align: center;">
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        <el-button type="primary" @click="confirm(ruleFormRef)">确认</el-button>
      </span>
    </template>
    <template #footer v-if="(dialogDatas?.type == 'check')">
      <span class="dialog-footer" style="display: block;text-align: center;">
        <el-button @click="resetForm(ruleFormRef)">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, onBeforeMount, toRefs, watch  } from 'vue';
import { getEnumListRequest, orgOptionsRequest,getCheckPointsOptionsRequest } from '@/api/common';
import {
  addDeviceRequest,
  getDeviceByIdRequest,
  editDeviceRequest
} from '@/api/checkPointEquipment';
import type { FormInstance, FormRules } from 'element-plus';
const emit = defineEmits(['updateList', 'changeCheck', 'update:dialogVisible']);
const visible = ref(false);
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  dialogDatas: {
    type: Object,
    default: () => { }
  }
});
const { dialogVisible, dialogDatas } = toRefs(props);
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  id:null,
  deviceId: null,
  orgId: '',
  checkPointsId: '',
  deviceType: '',
  status: ''
})
let enumListDatas = ref([]); //设备状态下拉数据
let enumListTypeDatas = ref([]); //设备类型下拉数据
// 校验
const rules = reactive<FormRules>({
  deviceId: [{ required: true, message: '请输入设备ID', trigger: 'change' }],
  orgId: [{ required: true, message: '选择归属组织', trigger: 'change' }],
  checkPointsId: [{ required: true, message: '选择归属检测点', trigger: 'change' }],
  deviceType: [{ required: true, message: '选择设备类型', trigger: 'change' }],
  status: [{ required: true, message: '选择启用状态', trigger: 'change' }],
})
let checkPointsOptionsDatas = reactive({}); //归属检测点下拉数据
let showOrgs = ref(true)
//  组织机构变化-》获取归属枚举值
const changeOrgId = async () => {
  showOrgs.value = false
  ruleForm.checkPointsId = '';
  const data: any = await getCheckPointsOptionsRequest({ orgId: ruleForm.orgId });
  checkPointsOptionsDatas = data.data;
  showOrgs.value = true
}
//提交
const confirm = async (formEl: FormInstance | undefined) => {
  console.log(ruleForm);
  
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let Url = dialogDatas.value.type == 'add' ? addDeviceRequest : editDeviceRequest;
      let res: any = await Url(ruleForm);
      if (res.code === 2000) {
        ElMessage.success('保存成功')
        emit("update:dialogVisible", false);
      } else {
        ElMessage.error(res.message)
      }
      formEl.resetFields()//重置
      emit('updateList')
    } else {
      console.log('保存失败', fields)
    }
  })
}
// 取消&重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  visible.value = false
  emit('updateList')
  emit("update:dialogVisible", false);
}
// 关闭
const closeDialog = () => {
  emit('updateList')
}
// 归属机构下拉
let orgIdDatas = ref([])
let showOrg = ref(true)
const getOrgOptionsDatas = async () => {
  showOrg.value = false
  const data: any = await orgOptionsRequest({ containBase: false });
  orgIdDatas.value = data.data;
  showOrg.value = true
};

/* 获取设备状态数据 */
const getEnumListDatas = async () => {
  const data: any = await getEnumListRequest({ enumName: 'DeviceStatusEnum' });
  enumListDatas.value = data.data;
};

/* 获取设备类型 */
const getEnumListTypeDatas = async () => {
  const data: any = await getEnumListRequest({ enumName: 'DeviceTypeEnum' });
  enumListTypeDatas.value = data.data
  
};

// 获取详情
const getDetailsFun = async () => {
  const data: any = await getDeviceByIdRequest({ deviceId: Number(dialogDatas.value.datas.deviceId),id: dialogDatas.value.datas.id });
  let res = data.data
  showOrgs.value = false
  const checkPoints: any = await getCheckPointsOptionsRequest({ orgId: res.orgId }); //根据组织id查询检测点下拉数据
  checkPointsOptionsDatas = checkPoints.data;
  showOrgs.value = true
  ruleForm.id = res.id
  ruleForm.deviceId = res.deviceId
  ruleForm.orgId = res.orgId
  ruleForm.checkPointsId = res.checkPointsId
  ruleForm.deviceType = res.deviceType
  ruleForm.status = res.status
}

onBeforeMount(async () => {
   getOrgOptionsDatas()
   getEnumListDatas()
   console.log('执行');
   
   getEnumListTypeDatas()
  if (dialogDatas.value.type == 'add') {
    // getMenuList()
  } else {
    getDetailsFun()
  }
})
</script>

<style lang="scss" scoped>
.el-dialog__footer{
  text-align: center;
}
</style>
